package com.snail.snailvr.views.fragments;

import android.app.Activity;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import com.box.androidsdk.content.BoxConfig;
import com.box.androidsdk.content.auth.BoxAuthentication;
import com.box.androidsdk.content.models.BoxFolder;
import com.box.androidsdk.content.models.BoxSession;
import com.snail.snailvr.R;
import com.snail.snailvr.disk.box.activities.BoxBrowseFileActivity;
import com.snail.snailvr.disk.dropbox.FilesActivity;
import com.snail.snailvr.event.BusProvider;
import com.snail.snailvr.event.OauthSuccessEvent;
import com.snail.snailvr.model.InputItem;
import com.snail.snailvr.network.providers.downloads.DownloadHelper;
import com.snail.snailvr.utils.Constant;
import com.snail.snailvr.utils.DatabaseUtils;
import com.snail.snailvr.utils.DialogUtils;
import com.snail.snailvr.utils.IntentUtils;
import com.snail.snailvr.views.adapter.InputAdapter;
import com.snail.snailvr.widget.HorizontalDividerItemDecoration;
import com.snail.snailvr.widget.WrapContentLinearLayoutManager;
import com.squareup.otto.Subscribe;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import rx.Subscription;

/**
 * 网盘以及WiFi传输
 * Created by snail on 16/4/14.
 */
public class InputFragment extends BaseFragment implements BoxAuthentication.AuthListener {

    @Bind(R.id.recycler_view)
    RecyclerView mRecyclerView;

    private BoxSession session;
    private InputAdapter mAdapter;
    private  List<InputItem> inputItems;

    private Subscription netDiskSubscription;
    private Subscription initNetDiskSubscription;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        BusProvider.getInstance().register(this);
    }

    @Override
    protected void handleIntent() {

    }

    @Override
    protected void initView() {
        setupRecyclerView();
    }

    private void setupRecyclerView() {
        mRecyclerView.setHasFixedSize(true);
        mRecyclerView.setLayoutManager(new WrapContentLinearLayoutManager(getActivity()));
        inputItems = new ArrayList<>(InputAdapter.INPUT_COUNT);
        mAdapter = new InputAdapter(getActivity(), inputItems);
        mRecyclerView.setAdapter(mAdapter);
        addDivider();

    }

    protected void addDivider() {
        HorizontalDividerItemDecoration horizontalDividerItemDecoration=new HorizontalDividerItemDecoration.Builder(getActivity())
                .paintProvider(mAdapter)
                .visibilityProvider(mAdapter)
                .marginProvider(mAdapter)
                .build();
        horizontalDividerItemDecoration.setBackgroundPaintColor(getResources().getColor(R.color.list_item_color_normal));
        mRecyclerView.addItemDecoration(horizontalDividerItemDecoration);
    }

    @Override
    protected void loadData() {
        getInputItems();
    }

    @Override
    protected int getLayoutId() {
        return R.layout.fragment_input;
    }

    /**
     * 连接到Box
     */
    private void linkBox() {
        BoxConfig.CLIENT_ID = Constant.BOX_CLIENT_ID;
        BoxConfig.CLIENT_SECRET = Constant.BOX_CLIENT_SECRET;
        BoxConfig.REDIRECT_URL = Constant.BOX_REDIRECT_URL;

        session = new BoxSession(getActivity());
        session.setSessionAuthListener(this);
        session.authenticate();
    }

    /**
     * 连接到Dropbox
     */
    private void linkDropBox() {
        startActivity( FilesActivity.getIntent(getActivity(), "", getString(R.string.all_files)));
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        loadWhenUserVisible(isVisibleToUser);
    }

    protected void loadWhenUserVisible(boolean isVisibleToUser) {
        if (isVisibleToUser) {
            if (!this.isFragmentVisible) {
                loadData();
                this.isFragmentVisible = true;
            }
        }
    }

    private void launchFilePicker() {
        startActivity(BoxBrowseFileActivity.getLaunchIntent(getActivity(), BoxFolder.createFromId("0"), session));
    }

    @Override
    public void onRefreshed(BoxAuthentication.BoxAuthenticationInfo info) {
    }

    @Override
    public void onAuthCreated(BoxAuthentication.BoxAuthenticationInfo info) {
        // 记录登录的账户信息
        InputItem item = new InputItem(info.getUser().getName(), getString(R.string.box));
        DatabaseUtils.saveConnectedInputItem(item);

        launchFilePicker();
    }

    @Override
    public void onAuthFailure(BoxAuthentication.BoxAuthenticationInfo info, Exception ex) {
    }

    @Override
    public void onLoggedOut(BoxAuthentication.BoxAuthenticationInfo info, Exception ex) {
    }

    @Override
    public void onResume() {
        super.onResume();
    }

    @Subscribe
    public void onOauthSuccess(OauthSuccessEvent event){
        // 重载数据 刷新UI
        getInputItems();
    }
    /**
     * 根据实际需求生成input items
     *
     * @return
     */
    private void getInputItems() {
        inputItems.clear();
        InputItem item = new InputItem(getString(R.string.input_via_wifi), InputAdapter.VIEW_TYPE_NORMAL, new InputViaWifiListener(getActivity()));
        inputItems.add(item);
        item = new InputItem(getString(R.string.input_via_url), InputAdapter.VIEW_TYPE_NORMAL, new InputViaUrlListener(this));
        inputItems.add(item);
        mAdapter.notifyDataSetChanged();
/*
        netDiskSubscription = DatabaseUtils.getAllNetDisk(new SingleSubscriber<List<InputItem>>() {
            @Override
            public void onSuccess(List<InputItem> list) {
                if (list!=null&&list.size() > 0) {
                    List<InputItem>connectList=new ArrayList<>(list.size());
                    List<InputItem>disConnectList=new ArrayList<>(list.size());

                    filterInputItem(list, connectList, disConnectList);

                    showConnectedInput(connectList);

                    showDisconnectInput(disConnectList);

                    mAdapter.notifyDataSetChanged();
                }else{
                    initNetDiskSubscription=DatabaseUtils.initNetDiskInfo(getActivity());

                }
            }

            @Override
            public void onError(Throwable error) {

            }
        });
*/

    }

    /**
     * 弹出输入URL的对话框
     */
    private void showInputUrlDialog(final Activity activity) {
        DialogUtils.showInputDialog(activity, false, getString(R.string.input_via_url), getString(R.string.enter_direct_url), getString(R.string.hint_direct_url),getString(R.string.CANCEL), getString(R.string.DOWNLOAD), false, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Object tag=v.getTag();
                if(tag!=null){
                    final String url=(String)tag;
                    if(!DownloadHelper.isFileExist(url)) {
                        if (DialogUtils.showJudgeNetDialog(activity, new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                DownloadHelper.startInputDownload(url);
                            }
                        }))
                            return;
                        DownloadHelper.startInputDownload(url);
                    }
                    else{
                        DialogUtils.showBasicDialog(activity, activity.getResources().getString(R.string.video_added),
                                activity.getResources().getString(R.string.download_again), activity.getResources().getString(R.string.string_no),
                                activity.getResources().getString(R.string.string_yes), false, new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        DownloadHelper.startInputDownload(url);
                                    }
                                });
                    }
                }
            }
        });
    }

    /**
     * 根据网盘链接状态过滤
     * @param list 所有网盘
     * @param connectList 已经授权
     * @param disConnectList 未授权
     */
    private void filterInputItem(List<InputItem> list, List<InputItem> connectList, List<InputItem> disConnectList) {
        for(InputItem inputItem:list){
            if(inputItem!=null){
                if(inputItem.isConnected())
                    connectList.add(inputItem);
                else{
                    disConnectList.add(inputItem);
                }
            }
        }
    }

    /**
     * 显示已经授权的网盘
     * @param connectList
     */
    private void showConnectedInput(List<InputItem> connectList) {
        //已经授权
        if(!connectList.isEmpty()) {
            // 添加提示项
            InputItem temp = new InputItem(getString(R.string.input_via_net_connect), InputAdapter.VIEW_TYPE_DIVIDER, null);
            inputItems.add(temp);

            // 添加内容项
            for (InputItem inputItem : connectList) {
                if (inputItem.getSubTitle().equals(getString(R.string.box))) {
                    inputItem.setIconResId(R.drawable.ic_input_box);
                    inputItem.setmOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            linkBox();
                        }
                    });
                    inputItem.setInputType(InputAdapter.VIEW_TYPE_WITH_ICON);
                } else if (inputItem.getSubTitle().equals(getString(R.string.dropBox))) {
                    inputItem.setIconResId(R.drawable.ic_input_dropbox);
                    inputItem.setmOnClickListener(new View.OnClickListener() {

                        @Override
                        public void onClick(View view) {
                            linkDropBox();
                        }
                    });
                    inputItem.setInputType(InputAdapter.VIEW_TYPE_WITH_ICON);
                }

                inputItems.add(inputItem);
            }
        }
    }
    /**
     * 显示未授权的网盘
     * @param disConnectList
     */
    private void showDisconnectInput(List<InputItem> disConnectList) {
        //未授权
        if(!disConnectList.isEmpty()){
            // 添加提示项
            InputItem temp = new InputItem(getString(R.string.input_via_net_disconnect), InputAdapter.VIEW_TYPE_DIVIDER, null);
            inputItems.add(temp);

            // 添加内容项
            for (InputItem inputItem : disConnectList) {
                if (inputItem.getSubTitle().equals(getString(R.string.box))) {
                    inputItem.setIconResId(R.drawable.ic_input_box_gray);
                    inputItem.setmOnClickListener(new LinkBoxListener(this));
                    inputItem.setInputType(InputAdapter.VIEW_TYPE_WITH_ICON);
                    inputItem.setTitle(getResources().getString(R.string.connect_to_box_account));
                } else if (inputItem.getSubTitle().equals(getString(R.string.dropBox))) {
                    inputItem.setIconResId(R.drawable.ic_input_dropbox_gray);
                    inputItem.setmOnClickListener(new LinkDropBoxListener(this));
                    inputItem.setInputType(InputAdapter.VIEW_TYPE_WITH_ICON);
                    inputItem.setTitle(getResources().getString(R.string.connect_to_dropbox_account));
                }

                inputItems.add(inputItem);
            }
        }
    }

    @Override
    public void onDestroy() {
        if (netDiskSubscription != null && !netDiskSubscription.isUnsubscribed())
            netDiskSubscription.unsubscribe();

        if(initNetDiskSubscription!=null&&!initNetDiskSubscription.isUnsubscribed())
            initNetDiskSubscription.unsubscribe();

        BusProvider.getInstance().unregister(this);
        super.onDestroy();
    }

    static class InputViaWifiListener implements View.OnClickListener{
        WeakReference<Activity>mActivityWeakReference;
        public InputViaWifiListener(Activity activity){
            mActivityWeakReference=new WeakReference<>(activity);
        }

        @Override
        public void onClick(View v) {
            if(mActivityWeakReference!=null&&mActivityWeakReference.get()!=null)
                IntentUtils.startWifiTransfer(mActivityWeakReference.get());
        }
    }

    static class InputViaUrlListener implements View.OnClickListener{
        WeakReference<InputFragment> mFragmentWeakReference;
        public InputViaUrlListener(InputFragment inputFragment){
            mFragmentWeakReference =new WeakReference<>(inputFragment);
        }

        @Override
        public void onClick(View v) {
            if(mFragmentWeakReference !=null&& mFragmentWeakReference.get()!=null) {
                InputFragment inputFragment= mFragmentWeakReference.get();
                inputFragment.showInputUrlDialog(inputFragment.getActivity());
            }
        }
    }

    static class LinkBoxListener implements View.OnClickListener{
        WeakReference<InputFragment> mFragmentWeakReference;
        public LinkBoxListener(InputFragment inputFragment){
            mFragmentWeakReference =new WeakReference<>(inputFragment);
        }

        @Override
        public void onClick(View v) {
            if(mFragmentWeakReference !=null&& mFragmentWeakReference.get()!=null) {
                InputFragment inputFragment= mFragmentWeakReference.get();
                inputFragment.linkBox();
            }
        }
    }

    static class LinkDropBoxListener implements View.OnClickListener{
        WeakReference<InputFragment> mFragmentWeakReference;
        public LinkDropBoxListener(InputFragment inputFragment){
            mFragmentWeakReference =new WeakReference<>(inputFragment);
        }

        @Override
        public void onClick(View v) {
            if(mFragmentWeakReference !=null&& mFragmentWeakReference.get()!=null) {
                InputFragment inputFragment= mFragmentWeakReference.get();
                inputFragment.linkDropBox();
            }
        }
    }

}
